package com.ysy.tz.mfg.controller;

import com.ysy.tz.core.engine.Modelable;
import com.ysy.tz.core.engine.ParameterInitializable;
import com.ysy.tz.core.selfcomp.CommonDialog;
import com.ysy.tz.core.selfcomp.CustomerAlert;
import com.ysy.tz.core.selfcomp.CustomerDatePicker;
import com.ysy.tz.core.selfcomp.PopupTextField;
import com.ysy.tz.core.selfcomp.TextChangeListener;
import com.ysy.tz.core.utils.SQLUtils;
import com.ysy.tz.core.utils.SessionUtils;
import com.ysy.tz.mfg.dao.CarcassInWarehouseDao;
import com.ysy.tz.mfg.dao.GradingDetailDao;
import com.ysy.tz.mfg.dao.ItemDao;
import com.ysy.tz.mfg.dao.SysMachineParamDao;
import com.ysy.tz.mfg.dao.WarehouseDao;
import com.ysy.tz.mfg.entity.CarcassInWarehouseEntity;
import com.ysy.tz.mfg.entity.GradingDetailEntity;
import com.ysy.tz.mfg.entity.ItemEntity;
import com.ysy.tz.mfg.entity.SysMachineParamEntity;
import com.ysy.tz.mfg.entity.UserEntity;
import com.ysy.tz.mfg.entity.WarehouseEntity;
import com.ysy.tz.mfg.equipment.scale.ToledoScale;
import com.ysy.tz.mfg.equipment.scale.WeightListener;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputControl;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import org.apache.commons.lang3.StringUtils;

public class CarcassInWarehouseController implements ParameterInitializable {
    @FXML
    CustomerDatePicker inWarehouseDate;
    @FXML
    PopupTextField itemTextField;
    @FXML
    PopupTextField warehouseTextField;
    @FXML
    TextField barcodeTextField;
    @FXML
    TextField invQtyTextField;
    @FXML
    TableView carcassInWarehouseTableView;
    @FXML
    Label gradingSupplier;
    @FXML
    Label gradingLevel;
    @FXML
    Label gradingSlaughterType;
    @FXML
    Label gradingGender;
    @FXML
    Label gradingBarcode;
    @FXML
    Label gradingBillNo;
    @FXML
    VBox barCodeBox;
    @FXML
    Label weightLabel;
    @FXML
    Label invqtyCountLabel;
    @FXML
    Label weightSumLabel;
    @FXML
    Label itemCountLabel;
    GradingDetailEntity gradingDetailEntity;
    ToledoScale toledoScale = new ToledoScale();
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    private HashMap<String, String> dictMap = new HashMap();

    public CarcassInWarehouseController() {
    }

    public void initialize(URL location, ResourceBundle resources, Object... params) {
        this.dictMap.put("B", "剥皮");
        this.dictMap.put("T", "腿毛");
        this.dictMap.put("G", "公");
        this.dictMap.put("M", "母");
        this.itemTextField.addTextChangeListener(new TextChangeListener<ItemEntity>() {
            public ObservableList textChanged(TextInputControl textField, String newValue) {
                return (ObservableList)SQLUtils.executeSQLWithReturn(ItemDao.class, (itemDao) -> {
                    try {
                        ItemEntity itemEntity = new ItemEntity();
                        int enterpriseId = ((UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER)).getEnterpriseId();
                        itemEntity.setEnterpriseId(enterpriseId);
                        itemEntity.setKeyWord(newValue);
                        ArrayList<ItemEntity> areaEntities = itemDao.listForPage(itemEntity);
                        return FXCollections.observableList(areaEntities);
                    } catch (Exception var5) {
                        var5.printStackTrace();
                        return null;
                    }
                });
            }

            public void PopupChoise(ItemEntity itemEntity) {
                CarcassInWarehouseController.this.itemTextField.setModel(itemEntity);
                CarcassInWarehouseController.this.warehouseTextField.requestFocus();
            }
        });
        this.warehouseTextField.addTextChangeListener(new TextChangeListener<WarehouseEntity>() {
            public ObservableList textChanged(TextInputControl textField, String newValue) {
                return (ObservableList)SQLUtils.executeSQLWithReturn(WarehouseDao.class, (warehouseDao) -> {
                    try {
                        WarehouseEntity warehouseEntity = new WarehouseEntity();
                        int enterpriseId = ((UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER)).getEnterpriseId();
                        warehouseEntity.setEnterpriseId(enterpriseId);
                        warehouseEntity.setKeyWord(newValue);
                        ArrayList<WarehouseEntity> warehouseEntities = warehouseDao.listForPage(warehouseEntity);
                        return FXCollections.observableList(warehouseEntities);
                    } catch (Exception var5) {
                        var5.printStackTrace();
                        return null;
                    }
                });
            }

            public void PopupChoise(WarehouseEntity warehouseEntity) {
                CarcassInWarehouseController.this.warehouseTextField.setModel(warehouseEntity);
                CarcassInWarehouseController.this.barcodeTextField.requestFocus();
            }
        });
        Platform.runLater(() -> {
            this.itemTextField.requestFocus();
        });
        this.initScale();
        this.showCurrentInWarehouseInfo();
        this.showStatisticsInfo();
    }

    private void initScale() {
        try {
            ArrayList<SysMachineParamEntity> sysMachineParamEntities = (ArrayList)SQLUtils.executeSQLWithReturnException(SysMachineParamDao.class, (sysMachineParamDao) -> {
                return sysMachineParamDao.searchSysMachineParamList("Dev010", "toledo", "weight");
            });
            sysMachineParamEntities.forEach((sysMachineParamEntity) -> {
                if (sysMachineParamEntity.getKeyPair().equals("baudrate")) {
                    this.toledoScale.setBaudrate(Integer.parseInt(sysMachineParamEntity.getPosParaValue()));
                } else if (sysMachineParamEntity.getKeyPair().equals("port")) {
                    this.toledoScale.setPortName(sysMachineParamEntity.getPosParaValue());
                } else if (sysMachineParamEntity.getKeyPair().equals("point")) {
                    this.toledoScale.setFractionDigits(Integer.parseInt(sysMachineParamEntity.getPosParaValue()));
                }

            });
            this.toledoScale.addWeightListener(new WeightListener() {
                public void obtainWeight(String weightStr) {
                    if (StringUtils.isNotBlank(weightStr) && Float.parseFloat(weightStr) != 0.0F) {
                        Platform.runLater(() -> {
                            CarcassInWarehouseController.this.weightLabel.setText(weightStr);
                        });
                    }

                }
            });
            this.toledoScale.connect();
        } catch (Exception var2) {
            var2.printStackTrace();
        }

    }

    public void unload() {
    }

    public void enterBarCode(KeyEvent keyEvent) {
        if (keyEvent.getCode() == KeyCode.ENTER) {
            String barCode = this.barcodeTextField.getText();
            this.barcodeTextField.setText("");
            if (StringUtils.isNotBlank(barCode)) {
                SQLUtils.executeSQL(GradingDetailDao.class, (gradingDetailDao) -> {
                    try {
                        int enterpriseId = ((UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER)).getEnterpriseId();
                        this.gradingDetailEntity = gradingDetailDao.selectGradingDetailByBarcode(enterpriseId, barCode);
                    } catch (Exception var4) {
                        var4.printStackTrace();
                    }

                });
            } else {
                this.gradingDetailEntity = null;
            }

            this.setGradingView(this.gradingDetailEntity);
        }

    }

    private void setGradingView(GradingDetailEntity gradingDetailEntity) {
        if (gradingDetailEntity != null) {
            this.gradingSupplier.setText(gradingDetailEntity.getSupplierName());
            this.gradingLevel.setText(gradingDetailEntity.getLevelCode());
            this.gradingSlaughterType.setText((String)this.dictMap.get("" + gradingDetailEntity.getSlaughterType()));
            this.gradingGender.setText((String)this.dictMap.get("" + gradingDetailEntity.getGender()));
            this.gradingBarcode.setText(gradingDetailEntity.getBarcode());
            this.gradingBillNo.setText(gradingDetailEntity.getBillNo());
            this.barCodeBox.setVisible(true);
        } else {
            this.barCodeBox.setVisible(false);
        }

    }

    public void submitInwarehouse(MouseEvent mouseEvent) {
        if (StringUtils.isBlank(this.inWarehouseDate.getEditor().getText())) {
            (new CustomerAlert(AlertType.WARNING, "请选择入库日期!", new ButtonType[0])).showAndWait();
            this.inWarehouseDate.requestFocus();
        } else if (this.itemTextField.getModel() == null) {
            (new CustomerAlert(AlertType.WARNING, "请选择品类!", new ButtonType[0])).showAndWait();
            this.itemTextField.requestFocus();
        } else if (this.warehouseTextField.getModel() == null) {
            (new CustomerAlert(AlertType.WARNING, "请选择库房!", new ButtonType[0])).showAndWait();
            this.warehouseTextField.requestFocus();
        } else if (this.gradingDetailEntity == null) {
            (new CustomerAlert(AlertType.WARNING, "请输入条码!", new ButtonType[0])).showAndWait();
            this.barcodeTextField.requestFocus();
        } else {
            UserEntity currentUser = (UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER);
            String workDay = "" + SessionUtils.getAttribute(SessionUtils.WORK_DAY);
            if (!this.checkBarCode(this.gradingDetailEntity.getBarcode(), currentUser.getEnterpriseId())) {
                (new CustomerAlert(AlertType.WARNING, "当前条码: " + this.gradingBarcode.getText() + " 已经入库!", new ButtonType[0])).showAndWait();
                this.gradingDetailEntity = null;
                this.barCodeBox.setVisible(false);
            } else {
                CarcassInWarehouseEntity carcassInWarehouseEntity = new CarcassInWarehouseEntity();
                carcassInWarehouseEntity.setEnterpriseId(currentUser.getEnterpriseId());
                carcassInWarehouseEntity.setWorkDay(workDay);
                carcassInWarehouseEntity.setWorkFlightsCode(currentUser.getFlightsCode());
                carcassInWarehouseEntity.setWarehouseId(((WarehouseEntity)this.warehouseTextField.getModel()).getWarehouseId());
                carcassInWarehouseEntity.setItemId(((ItemEntity)this.itemTextField.getModel()).getItemId());
                carcassInWarehouseEntity.setSupplierId(this.gradingDetailEntity.getSupplierId());
                carcassInWarehouseEntity.setBarcode(this.gradingDetailEntity.getBarcode());
                carcassInWarehouseEntity.setBillNo(this.gradingDetailEntity.getBillNo());
                carcassInWarehouseEntity.setLevelCode(this.gradingDetailEntity.getLevelCode());
                carcassInWarehouseEntity.setSlaughterType(this.gradingDetailEntity.getSlaughterType());
                carcassInWarehouseEntity.setGender(this.gradingDetailEntity.getGender());
                carcassInWarehouseEntity.setInvqty(Integer.parseInt(this.invQtyTextField.getText()));
                carcassInWarehouseEntity.setWeight(new BigDecimal(this.weightLabel.getText()));
                carcassInWarehouseEntity.setCreateUserCode(currentUser.getUserCode());
                carcassInWarehouseEntity.setCreateUserName(currentUser.getUserName());
                carcassInWarehouseEntity.setInWarehouseDay(this.inWarehouseDate.getEditor().getText());
                boolean success = false;

                try {
                    SQLUtils.executeSQLException(CarcassInWarehouseDao.class, (carcassInWarehouseDao) -> {
                        carcassInWarehouseDao.save(carcassInWarehouseEntity);
                    });
                    success = true;
                    this.gradingDetailEntity = null;
                    this.barCodeBox.setVisible(false);
                } catch (Exception var7) {
                    var7.printStackTrace();
                    (new CustomerAlert(AlertType.WARNING, "插入数据库异常，请联系管理员!", new ButtonType[0])).showAndWait();
                }

                if (success) {
                    this.showCurrentInWarehouseInfo();
                    this.showStatisticsInfo();
                    this.barcodeTextField.requestFocus();
                }

            }
        }
    }

    private boolean checkBarCode(String barcode, Integer enterpriseId) {
        try {
            CarcassInWarehouseEntity carcassInWarehouseEntity = (CarcassInWarehouseEntity)SQLUtils.executeSQLWithReturnException(CarcassInWarehouseDao.class, (carcassInWarehouseDao) -> {
                return carcassInWarehouseDao.exitsCarcassInWarehouseRecord(barcode, enterpriseId);
            });
            return carcassInWarehouseEntity == null;
        } catch (Exception var4) {
            var4.printStackTrace();
            return false;
        }
    }

    private void showCurrentInWarehouseInfo() {
        UserEntity currentUser = (UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER);
        String workDay = "" + SessionUtils.getAttribute(SessionUtils.WORK_DAY);

        try {
            ArrayList<CarcassInWarehouseEntity> carcassInWarehouseEntities = (ArrayList)SQLUtils.executeSQLWithReturnException(CarcassInWarehouseDao.class, (carcassInWarehouseDao) -> {
                return carcassInWarehouseDao.searchLastTopCarcaseInWarehouseRecordOneDay(currentUser.getUserCode(), currentUser.getEnterpriseId(), workDay, currentUser.getFlightsCode(), 7);
            });
            this.carcassInWarehouseTableView.setItems(FXCollections.observableList(carcassInWarehouseEntities));
        } catch (Exception var4) {
            var4.printStackTrace();
        }

    }

    private void showStatisticsInfo() {
        UserEntity currentUser = (UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER);
        String workDay = "" + SessionUtils.getAttribute(SessionUtils.WORK_DAY);

        try {
            CarcassInWarehouseEntity carcassInWarehouseEntity = (CarcassInWarehouseEntity)SQLUtils.executeSQLWithReturnException(CarcassInWarehouseDao.class, (carcassInWarehouseDao) -> {
                return carcassInWarehouseDao.searchStatisticsRecordOneDay(currentUser.getUserCode(), currentUser.getEnterpriseId(), workDay, currentUser.getFlightsCode());
            });
            if (carcassInWarehouseEntity != null && carcassInWarehouseEntity.getWeight() != null) {
                this.invqtyCountLabel.setText(carcassInWarehouseEntity.getInvqty().toString());
                this.itemCountLabel.setText(carcassInWarehouseEntity.getItemId().toString());
                this.weightSumLabel.setText(this.decimalFormat.format(carcassInWarehouseEntity.getWeight()));
            }
        } catch (Exception var4) {
            var4.printStackTrace();
        }

    }

    public void clearChoise(MouseEvent mouseEvent) {
        this.itemTextField.setModel((Modelable)null);
        this.warehouseTextField.setModel((Modelable)null);
        this.gradingDetailEntity = null;
        this.setGradingView(this.gradingDetailEntity);
    }

    public void showInWarehouseDialog(MouseEvent mouseEvent) {
        Dialog dialog = CommonDialog.loadFXMLDialog("羊胴体入库明细查询", "CarcassInWarehouseList", "CarcassInWarehouse", new Object[0]);
        dialog.showAndWait();
    }
}
